package main

import (
	"flag"
	"fmt"
	"go_upload_server/libs"
	"log"
	"net/http"
	"os"
	"runtime"
)

func main() {

	flag.Parse()
	//导入配置文件
	libs.Conf = libs.ConfigRead()
	logFile, err := os.Create(libs.Conf.Log)
	if err != nil {
		fmt.Println(err)
	}
	runtime.GOMAXPROCS(libs.Conf.MaxProc)

	libs.Loger = log.New(logFile, "", log.Ldate|log.Ltime|log.Lshortfile)
	libs.Loger.Printf("Upload Server Start...")

	//启动一个redis池
	if libs.Conf.RedisAddr != "" {
		libs.RedisInit(libs.Conf.RedisAddr, libs.Conf.RedisDB)
	}

	//fmt.Println(libs.RegKeyId("1"))
	//fmt.Println(libs.RegKeyId("2"))
	//fmt.Println(libs.RegKeyId("3"))
	mux := http.NewServeMux()
	//API get imgid
	mux.HandleFunc("/upload/api/", libs.UploadApiHandler)
	//upload server
	mux.HandleFunc("/upload/", libs.UploadHandler)
	// http://ip:post/abcfdsajkflejia.jpg or https://ip:post/fdasjekf.jpg!10_10
	mux.HandleFunc("/k/", libs.DownloadHandler)
	//ID http://ip:post/id/abc
	mux.HandleFunc("/id/", libs.HashIdHandler)
	//static file handler.
	mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("public"))))

	http.ListenAndServe(libs.Conf.TCPAddr, libs.LimitConn(mux))
	http.ListenAndServeTLS(libs.Conf.TLSAddr, libs.Conf.TLSCert, libs.Conf.TLSKey, libs.LimitConn(mux))

	libs.SignalInit()
}
